# -*- coding: utf-8 -*-
import datetime
import json
import os

import requests
import random
import xlrd
import time
from bs4 import BeautifulSoup
from Teacher import Teacher
from emailTest import ToEmail

import logging
from logging.handlers import TimedRotatingFileHandler

# 保存评论内容
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
header = {
    "Referer": "http://wisezone.zensian.com/user/student_login.jsp",
    'User-Agent': userAgent,
}
session = requests.session()


def mafengwoLogin(username, password, email, flag):
    print("开始登录智云作业系统")
    postUrl = "http://wisezone.zensian.com/user/teacher/passwordLogin"
    postData = {
        "phoneNum1": username,
        "password": password,
    }
    responseRes = session.post(postUrl, data=postData, headers=header)
    print(json.loads(responseRes.text)["message"])
    if json.loads(responseRes.text)["result"] == True:
        print("开始查询老师得批改作业的内容")
        ss = session.get("http://wisezone.zensian.com/user/homework/findNotCommentHomeworkByTeacher", data=postData,
                         headers=header)
        soup = BeautifulSoup(ss.content.decode(), 'html.parser')
        links = soup.find(attrs={'class': 'ypryl'})
        if links == None:
            print("暂无作业可以批改")
            return
        teacherId = str(links.find("a")['href']).split("teacherId=")[1].split("&")[0]
        strs = "http://wisezone.zensian.com/user/homework/findNotCommentHomeworkByTeacherYiBu?teacherId={}&pageNum=1&pageSize=2000".format(
            teacherId)
        sss = session.get(strs, data=postData, headers=header)
        arr = json.loads(sss.text)
        contextarray = []
        for i in arr:
            student = i["students"][0]["name"]
            con = commenttt(flag)
            task(teacherId, i["id"], con, flag)
            contextarray.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + i["students"][0]["name"] + "作业"
                                + "批改完成" + '\n' + '\t')
            time.sleep(1)
            print("正在批改:" + student + "作业" + '\t' + "批改内容为:" + con)
            printlog("正在批改:" + student + "作业" + "批改内容为:" + con, flag)
        tomeail = ToEmail()
        tomeail.toEmail("以批改" + student + "作业 内容为:" + con + "".join(contextarray), email)
    else:
        print("登录失败")


def task(teacherId, taskId, context, flag):
    postUrl = "http://wisezone.zensian.com/user/homework/commentHomework"
    score = random.randrange(75, 86, 1)
    starb = 0
    if score > 70 and score < 80:
        starb = 3
    elif score > 80 and score < 90:
        starb = 4
    else:
        starb = 5
    postData = {
        "teacherId": teacherId,
        "id": taskId,
        "score": score,
        "star": starb,
        "tagEvaluate": ramenpinglun(flag),
        "descEvaluate": context
    }
    session.post(postUrl, data=postData, headers=header)
    return


# 获取标签
def ramenpinglun(flag):
    codeArry = ["操作逻辑", "代码规范", "逻辑清晰"]
    arry = ["设计规范", "版式结构", "对比关系"]
    if flag == 1:
        return codeArry[random.randint(1, len(codeArry) - 1)]
    else:
        return arry[random.randint(1, len(arry) - 1)]


# 获取excel中评论
def commenttt(flag):
    if flag == 1:
        codeContext = []
        if len(codeContext) > 0:
            return str(codeContext[random.randint(0, len(codeContext)) - 1])
        else:
            data = xlrd.open_workbook("comment.xls")
            table = data.sheet_by_name('Sheet1')
            for i in table.get_rows():
                str1 = str(i[0].value).replace(" ", "")
                if len(str1) > 0:
                    codeContext.append(str1)
                else:
                    continue
            return str(codeContext[random.randint(0, len(codeContext)) - 1])
    else:
        context = []
        data = xlrd.open_workbook("sheji.xlsx")
        table = data.sheet_by_name('Sheet1')
        for i in table.get_rows():
            str1 = str(i[0].value).replace(" ", "")
            if len(str1) > 0:
                context.append(str1)
            else:
                continue
        return str(context[random.randint(0, len(context)) - 1])


def printlog(str, flag):
    isExists1 = os.path.exists("wcc")
    if not isExists1:
        os.makedirs("wcc")
    else:
        print("wcc" + "目录已经存在")

    isExists2 = os.path.exists("houge")
    if not isExists2:
        os.makedirs("houge")
    else:
        print("wcc" + "目录已经存在")
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.INFO)
    if flag == 1:
        ch = TimedRotatingFileHandler("wcc\{}".format(datetime.datetime.now().strftime('%Y-%m-%d')), when='D', encoding="utf-8")
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        logger.info(str)
    else:
        ch = TimedRotatingFileHandler("houge\{}.log".format(datetime.datetime.now().strftime('%Y-%m-%d')), when='D', encoding="utf-8")
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        logger.info(str)



if __name__ == "__main__":
        te2 = Teacher("18587781058", "wangcong1993", "18587781058@163.com", 1)
        te1 = Teacher("15536511680", "hhb123456", "369355449@qq.com", 2)
        teacherArray = [te1, te2]
        for i in teacherArray:
            mafengwoLogin(i.username, i.password, i.email, i.flag)
